#!/usr/bin/env python 
# -*- coding:utf-8 -*-

import sys, os, time, atexit, string
from signal import SIGTERM
from Ump import ua_main
app = ua_main.app
home = os.path.abspath(os.path.split(os.path.realpath(__file__))[0])


class Daemon:
    def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
        #需要获取调试信息，改为stdin='/dev/stdin', stdout='/dev/stdout', stderr='/dev/stderr'，以root身份运行。
        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr
        self.pidfile = pidfile
  
    def _daemonize(self):
        try:
            pid = os.fork()
            if pid > 0:
                #退出主进程
                sys.exit(0)
        except OSError, e:
            print e
            sys.stderr.write('fork #1 failed: %d (%s)\n' % (e.errno, e.strerror))
            sys.exit(1)
  
        os.chdir("/")
        os.setsid()
        os.umask(0)
  
        #print '@2'
        ##创建子进程
        #try:
        #    pid = os.fork()
        #    print pid,'==='
#       #     if pid > 0:
#       #         sys.exit(0)
        #except OSError, e:
        #    print e
        #    sys.stderr.write('fork #2 failed: %d (%s)\n' % (e.errno, e.strerror))
        #    sys.exit(1)
  
        #重定向文件描述符
        #sys.stdout.flush()
        #sys.stderr.flush()
        #print 'dddd'
        #si = file(self.stdin, 'r')
        #so = file(self.stdout, 'a+')
        #se = file(self.stderr, 'a+', 0)
        #os.dup2(si.fileno(), sys.stdin.fileno())
        #os.dup2(so.fileno(), sys.stdout.fileno())
        #os.dup2(se.fileno(), sys.stderr.fileno())
  
        #创建processid文件
#        atexit.register(self.delpid)
        pid = str(os.getpid())
        file(self.pidfile,'w+').write('%s\n' % pid)
  
    def delpid(self):
        os.remove(self.pidfile)

    def start(self,port='8080'):
        #检查pid文件是否存在以探测是否存在进程
        try:
            pf = file(self.pidfile,'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None
        except Exception,e:
            pid = None
  
        if pid:
            message = 'pidfile %s already exist. Daemon already running?\n'
            sys.stderr.write(message % self.pidfile)
            sys.exit(1)
            
        #启动监控
        self._daemonize()
        self._run(port)

    def stop(self):
        #从pid文件中获取pid
        os.system("kill -9 `ps aux | grep ua_main.py |grep -v grep|awk '{print $2}'|head -1`")
        if os.path.exists(self.pidfile):
            os.remove(self.pidfile)

    def _stop(self):
        try:
            pf = file(self.pidfile,'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None
  
        if not pid:
            message = 'pidfile %s does not exist. Daemon not running?\n'
            sys.stderr.write(message % self.pidfile)
            return #重启不报错

        #杀进程
        try:
            print pid
            os.kill(pid, SIGTERM)
            time.sleep(0.1)
        except OSError, err:
            err = str(err)
            if err.find('No such process') > 0:
                if os.path.exists(self.pidfile):
                    os.remove(self.pidfile)
            else:
                print str(err)
                sys.exit(1)

    def restart(self):
        self.stop()
        self.start()
    
    def _run(self,port):
#        os.system('python /root/Desktop/work/git/ump/manager.py 999 &')
#        start()
        cmd = 'python %s/Ump/ua_main.py %s > /var/umplog 2>&1 &'%(home,port)
        os.system(cmd)
        print 'http://0.0.0.0:%s'%port
#        print c,'=========='
#        app.run()
    

if __name__ == '__main__':
    daemon = Daemon('/var/run/ump.pid')
    if len(sys.argv) >= 2:
        port = '8080'
        if len(sys.argv) > 2:
            port = sys.argv[2]
        if '--start' == sys.argv[1]:
            daemon.start(port)
        elif '--stop' == sys.argv[1]:
            daemon.stop()
        elif '--restart' == sys.argv[1]:
            daemon.restart()
        else:
            print 'Unknown command'
            sys.exit(2)
        sys.exit(0)
    else:
        print 'usage: %s --start|--stop|--restart' % sys.argv[0]
        sys.exit(2)
